import { ref, watch } from "vue";
import { i18n } from "@/i18n";
import { FormConfigType, getDefaultFormConfig } from "@/views/formgen/components/GenerateForm/types/form";
import { useUserForm } from "@/views/formgen/components/GenerateForm/hooks/useUserForm";

export function useAddOrUpdate(emit: any, props: any) {
  const formParseKey = ref(new Date().getTime());
  const dialogFormVisible = ref(false);
  const formModel = ref({});
  const title = ref(i18n.global.t("common.add"));
  const formConf = ref<FormConfigType>({
    ...getDefaultFormConfig(),
    formBtns: false
  });

  const userFormStore = useUserForm();

  // Watch for changes in props.fields
  watch(
    () => props.fields,
    val => {
      formConf.value.fields = val;
    },
    { deep: true, immediate: true }
  );

  const generateFormRef = ref<any>(null);

  // Method to handle form submission
  const handleUpdate = () => {
    console.log(generateFormRef.value.genFormRef);
    generateFormRef.value.genFormRef.validate((valid: boolean) => {
      if (valid) {
        dialogFormVisible.value = false;
        console.log(generateFormRef.value.getFormModel);
        emit("submit", generateFormRef.value.getFormModel);
      }
    });
  };

  // Method to show dialog
  const showDialog = (data: any) => {
    console.log(formConf.value);
    if (data) {
      formModel.value = data;
      title.value = i18n.global.t("common.edit");
    } else {
      formModel.value = {};
      userFormStore.setFormModel({});
      title.value = i18n.global.t("common.add");
    }
    dialogFormVisible.value = true;
    formParseKey.value = new Date().getTime();
  };

  return {
    formParseKey,
    dialogFormVisible,
    formModel,
    title,
    formConf,
    generateFormRef,
    handleUpdate,
    showDialog,
    userFormStore
  };
}
